"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

from msnp.service.network.model.ReliableTransportModel import ReliableTransportType
from msnp.logger import Logger
from msnp.service import utils

"""This module contains a queue for reliable transport messages together some needed functions:
- add an entry
- delete an entry
- check if an entry is contained in the queue."""

#the queue
__transportQueue = []
#delete entries that are older than 3 minutes
__threshold = 180

def addRTEntry(entry):
    """This function adds an entry to the queue.
    
    The function first cleans the queue (remove entries older than the threshold allows it) 
    and if the queue contains no such entry it adds the given entry.
    
    Args:
        entry: the ReliableTransportMessage instance
    """
    
    global __transportQueue
    __cleanTransportQueue(entry)
    if __alreadyProcessed(entry) == False:
        __transportQueue.append(entry)
        return True
    return False
    
    
def deleteRTEntry(entry):
    """This function deletes an entry from the queue.
    
    Args:
        entry: the ReliableTransportMessage instance"""
        
    global __transportQueue
    for e in __transportQueue:
        #all attributes have to correspond
        if e.isEqual(entry):
            __transportQueue.remove(e)
    
    
def __cleanTransportQueue(entry):
    """This function cleans the queue.
    
    It removes all entries from the queue that are older than the threshold allows it.
    
    Args:
        entry: the ReliableTransportMessage instance"""

    global __transportQueue
    global __threshold
    currTime = utils.DateFormatter.formatTimeAsFloat() 
    for e in __transportQueue:
        if currTime - e.getTimestamp() > __threshold or (entry.isUseBroadcast() and (e.isUseBroadcast() == False) and e.isEqual(entry)):
            Logger.info("remove entry from transport queue: type=" + e.getType() + ", compareIdentity=" + e.getCompareIdentity().getName())
            __transportQueue.remove(e)
    
    
def __alreadyProcessed(entry):
    """This function checks whether the given entry is already contained in the queue.
    
    Args:
        entry: the ReliableTransportMessage instance
        
    Returns
        True if the entry is already contained in the queue, False otherwise."""
        
    global __transportQueue
    for e in __transportQueue:
        #all attributes have to correspond
        if e.isEqual(entry):
            Logger.info("message already in queue")
            return True
    return False


def alreadyProcessedCrashMessage(crashedName):
    """This function checks whether a crash message for the given name is already in the queue.
    
    Args:
        crashedName: the name of the crashed peer (string)
        
    Returns:
        True if a crash message for the given name is already in the queue, False otherwise.
    """
    
    global  __transportQueue 
    for e in __transportQueue:
        #only name and type have to correspond
        if e.getType() == ReliableTransportType.SEARCHSUCCESSOR and e.getCrashedIdentity().getName() == crashedName:
            return True
    return False
